import cv2
import numpy as np
from matplotlib import pyplot as plt

image = cv2.imread('../IMAGES/football.jpg',0)
img = image.copy()
rows, cols = img.shape
print(img.shape)

template = cv2.imread('../IMAGES/football_ball.jpg',0)
h, w = template.shape
print(template.shape)

img_norm = img/255
template_norm = template/255

img_norm = img_norm - np.mean(img_norm)
template_norm = template_norm - np.mean(template_norm)

def convolution(image, kernel):
    conv = np.zeros((rows - h + 1, cols - w + 1))
    for i in range(rows - h + 1):
        for j in range(cols - w + 1):
            img_array = np.array(image[i:i + w, j:j + h])
            conv[i, j] = np.sum(img_array * kernel)
    return conv

conv = convolution(img_norm, template_norm)

cv2.normalize(conv,conv,0,255,cv2.NORM_MINMAX)
conv = np.uint8(conv)
c_h, c_w = np.unravel_index(np.argmax(conv), conv.shape)
print(c_h, c_w)

cv2.rectangle(image,(c_w, c_h),(c_w + 40, c_h + 40),(255,255,255),2)

plt.subplot(121)
plt.imshow(image,cmap = 'gray')
plt.subplot(122)
plt.imshow(conv,cmap = 'gray')
plt.show()
